package com.i.userservice.listener;

import com.i.piccommon.constant.RedisConstants;
import com.i.piccommon.constant.Status;
import com.i.piccommon.exception.BusinessException;
import com.i.userservice.config.MQConfig;
import com.i.userservice.domain.dto.MailDTO;
import com.i.userservice.service.IMailService;
import com.i.userservice.util.ValidateCodeUtil;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/10/24
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MailListener {

    private final IMailService mailSenderService;
    private final StringRedisTemplate redisTemplate;

    @RabbitListener(queues = MQConfig.QUEUE_NAME)
    public void sendRegisterMail(Message message, Channel channel, String email) throws IOException {
        log.info("为用户发送注册信息:[{}]", email);
        try {
            MailDTO mailDTO = new MailDTO();
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("email",email);
            String code = ValidateCodeUtil.generateRandomString(6);
            redisTemplate.opsForValue().set(RedisConstants.REGISTER_CODE_KEY_PREFIX + email,code,3, TimeUnit.MINUTES);
            mailDTO.setTo(Collections.singletonList(email)).setSubject("注册通知")
                    .setContextVar(userMap).setText("验证码为:" + code);
            mailSenderService.sendHtmlMail(mailDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("邮件发送成功");
        } catch (IOException e) {
            log.error("邮件发送失败:{}", e.getMessage());
            // 回复消息处理失败，并重新入队
//             channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            throw new BusinessException(Status.MAIL_SEND_FAILED.getMessage());
        }
    }
    @RabbitListener(queues = MQConfig.DEAD_QUEUE)
    public void listener(Message message, Channel channel) throws IOException {
        log.error("死信队列收到信息:唯一标识:{}",message.getMessageProperties().getCorrelationId());
        log.error("死信队列收到信息:messageID:{}",message.getMessageProperties().getMessageId());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
